<template>
    <Breadcrumb :datas="[`管理系统`, `公告管理`]">
        <el-button plain type="primary" @click="adddrawer.show = true"
            ><el-icon><Plus /></el-icon>新增公告</el-button
        >
    </Breadcrumb>
    <el-table :data="notices" style="width: 100%" empty-text="没有数据">
        <el-table-column label="标题" prop="title" />
        <el-table-column label="创建日期" prop="createdAt" />
        <el-table-column label="状态">
            <template #default="scope">
                <el-tag v-if="scope.row.isActive" type="success">已启用</el-tag>
                <el-tag type="danger" v-else>已禁用</el-tag>
            </template>
        </el-table-column>
        <el-table-column label="查看详情">
            <template #default="scope">
                <el-link
                    type="primary"
                    @click="router.replace(`/notices/${scope.row._id}`)"
                >
                    <el-icon>
                        <Link />
                    </el-icon>
                    查看详情
                </el-link>
            </template>
        </el-table-column>
        <el-table-column align="right" width="320">
            <template #header>
                <el-input
                    v-model.trim="params.keywords"
                    placeholder="请输入搜索关键词"
                    size="large"
                    clearable
                    @keyup.enter="searchHandle"
                    @clear="searchHandle"
                >
                    <template #append>
                        <el-button
                            @click="searchHandle"
                            size="large"
                            plain
                            type="primary"
                            >搜索</el-button
                        >
                    </template>
                </el-input>
            </template>
            <template #default="scope">
                <el-switch
                    size="large"
                    style="margin-right: 10px"
                    v-model="scope.row.isActive"
                    inline-prompt
                    :active-value="false"
                    :inactive-value="true"
                    active-text="启用"
                    inactive-text="禁用"
                    @change="updateStatus(scope.row)"
                ></el-switch>
                <el-button
                    type="primary"
                    plain
                    @click="showUpdate(scope.row._id)"
                    >修改</el-button
                >
                <DeleteConfirm :confirm="() => deleteEvent(scope.row._id)" />
            </template>
        </el-table-column>
    </el-table>
    <div class="pagination">
        <el-pagination
            :page-size="params.pagesize"
            background
            layout="prev, pager, next"
            :total="total"
            :current-page="params.pageno"
            :hide-on-single-page="true"
            @current-change="(page) => pageChange(page)"
        />
    </div>
    <Teleport to="body">
        <!-- 新增公告 -->
        <AddDrawer
            :show="adddrawer.show"
            :size="500"
            title="新增公告"
            :close="closeDrawer"
        >
            <template #body>
                <el-form-item label="标题" size="large">
                    <el-input
                        type="text"
                        placeholder="请输入标题"
                        size="large"
                        v-model.trim="adddrawer.data.title"
                        :prefix-icon="Message"
                    />
                </el-form-item>
                <el-form-item label="公告内容" size="large">
                    <Editor ref="editorRef" />
                </el-form-item>
            </template>
            <template #footer>
                <el-button size="large" @click="closeDrawer">取消</el-button>
                <el-button size="large" type="primary" @click="addNotice"
                    >提交</el-button
                >
            </template>
        </AddDrawer>
        <!-- 修改公告 -->
        <el-dialog
            v-model="updatepop.show"
            align-center
            width="660"
            title="分类修改"
            class="update-dialog"
        >
            <el-form label-width="80px" label-position="top">
                <el-form-item label="公告标题">
                    <el-input
                        v-model="updatepop.data.title"
                        size="large"
                        :prefix-icon="Notebook"
                    />
                </el-form-item>
                <el-form-item label="公告内容" size="large">
                    <Editor ref="updateEditorRef" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button size="large" @click="updatepop.show = false"
                    >取消</el-button
                >
                <el-button size="large" type="primary" @click="updateNotice"
                    >确定</el-button
                >
            </template>
        </el-dialog>
    </Teleport>
</template>

<script setup>
import { useRouter } from "vue-router";
import { Message, Plus, Notebook, Link } from "@element-plus/icons-vue";
import Breadcrumb from "@/components/breadcrumb";
import {
    NoticeList,
    AddNotice,
    DeleteNotice,
    UpdateNotice,
    NoticeDetail
} from "@/api/notices";
import AddDrawer from "@/components/drawer";
import DeleteConfirm from "@/components/confirm";
import Editor from "./editor";
import { ref, reactive, onMounted, nextTick } from "vue";
import { ElMessage } from "element-plus";

const router = useRouter();
const editorRef = ref(null);
const updateEditorRef = ref(null);

const adddrawer = reactive({
    show: false,
    data: {}
});
const updatepop = reactive({
    show: false,
    data: {}
});

const notices = ref([]);
const total = ref(0);
const params = reactive({
    pageno: 1,
    pagesize: 10,
    keywords: ""
});
// 关闭抽屉
const closeDrawer = () => {
    adddrawer.show = false;
};

// 确定删除
const deleteEvent = async (id) => {
    const res = await DeleteNotice(id);
    if (res) {
        ElMessage.success("删除成功");
        notices.value = notices.value.filter((item) => item._id !== id);
        total.value--;
    }
};

// 搜索
const searchHandle = async () => {
    params.pageno = 1;
    getNotice();
};
// 新增轮播
const addNotice = async () => {
    if (!adddrawer.data.title) {
        return ElMessage.error("请输入公告标题");
    }
    if (!editorRef.value.content) {
        return ElMessage.error("请输入公告内容");
    }
    const res = await AddNotice({
        title: adddrawer.data.title,
        content: editorRef.value.content
    });
    if (res) {
        notices.value.unshift(res);
        adddrawer.data = {};
        adddrawer.show = false;
        editorRef.value.clear();
        total.value++;
    }
};

// 获取数据
const getNotice = async () => {
    const res = await NoticeList({
        pageno: params.pageno,
        pagesize: params.pagesize,
        keywords: params.keywords
    });
    if (res) {
        total.value = res.total * 1;
        notices.value = res.list;
    }
};

// 修改轮播状态
const updateStatus = async ({ _id, isActive }) => {
    const status = isActive ? true : false;
    const res = await UpdateNotice(_id, { isActive: status });
    if (res) {
        ElMessage.success("公告状态修改成功");
        notices.value.map((item) => {
            if (item._id == _id) {
                item.isActive = status;
            }
        });
    }
};

// 分页
const pageChange = (pageno) => {
    params.pageno = pageno;
    getNotice();
};

// 修改显示
const showUpdate = async (id) => {
    const res = await NoticeDetail(id);
    if (res) {
        updatepop.data = res;
        updatepop.show = true;
        nextTick(() => {
            updateEditorRef.value.setContent(res.content);
        });
    }
};

// 修改公告
const updateNotice = async () => {
    if (!updatepop.data.title) {
        return ElMessage.error("请输入标题");
    }
    if (!updateEditorRef.value.content) {
        return ElMessage.error("公告内容不能为空");
    }
    const res = await UpdateNotice(updatepop.data._id, {
        title: updatepop.data.title,
        content: updateEditorRef.value.content
    });
    if (res) {
        ElMessage.success("修改成功");
        notices.value.map((item) => {
            if (item._id == updatepop.data._id) {
                item.title = updatepop.data.title;
            }
        });
        updatepop.show = false;
    }
};
onMounted(() => {
    getNotice();
});
</script>

<style lang="scss" scoped>
.add-drawer {
    h1 {
        font-weight: bold;
        align-items: center;
    }
    .footer {
        padding-bottom: 3em;
    }
}
</style>
